import os
import sys
import re

kResultPath = os.path.join(os.path.dirname(__file__), "result")

def walk_path_and_check(root_path):
    target_file_exts = {".c", ".cc", ".cpp", '.h', ".hpp"}
    for dirpath, dirnames, filenames in os.walk(root_path):
        for filename in filenames:
            _, extension = os.path.splitext(filename)
            if extension in target_file_exts:
                full_path = os.path.join(dirpath, filename)
                check_redundant_space(full_path)

def has_invalid_spaces(code_text) -> bool:
    partten = r"\s{2,}"
    filter_patterns = r"\/{2}|\\|namespace|@|[|]|[*]"
    text = code_text.strip()
    if re.search(filter_patterns, text) is not None:
        return False
    ret = re.search(partten, text)
    if ret is not None:
        return True
    return False

def check_redundant_space(filepath):
    with open(filepath, 'r') as fin, open(os.path.join(kResultPath, "air.log"),'a') as fout:
        for line_num, code_text in enumerate(fin, 1):
            if has_invalid_spaces(code_text):
                item = f"{filepath}:{line_num}, {code_text}"
                print(f"{filepath}:{line_num}, {code_text}", end="")
                fout.write(item)
                
        


if __name__ == "__main__":
    if len(sys.argv) > 1:
        repo_paths = sys.argv[1:]
        print(f"Root path is set to {repo_paths}")
    else:
        print("Please input at least One root path!")

    for path in repo_paths:
        root_path = os.path.abspath(path)
        walk_path_and_check(root_path)

'''
python check_redundant_spaces.py ~/Works/blue_code/air/base ~/Works/blue_code/air/compiler/ ~/Works/blue_code/air/executor ~/Works/blue_code/air/inc ~/Works/blue_code/air/runner ~/Works/blue_code/air/runtime
grep  -rnE "LOG" ./result/ | wc -l
'''